package net.xiaosaguo.mymall.product.service.impl;


import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.xiaosaguo.common.constant.ProductConstant;
import net.xiaosaguo.common.pojo.dto.SkuHasStockDTO;
import net.xiaosaguo.common.pojo.dto.SkuReductionDTO;
import net.xiaosaguo.common.pojo.dto.SpuBoundDTO;
import net.xiaosaguo.common.pojo.dto.es.SkuEsModel;
import net.xiaosaguo.common.utils.PageUtils;
import net.xiaosaguo.common.utils.Query;
import net.xiaosaguo.common.utils.R;
import net.xiaosaguo.mymall.product.dao.SpuInfoDao;
import net.xiaosaguo.mymall.product.entity.*;
import net.xiaosaguo.mymall.product.feign.CouponFeignService;
import net.xiaosaguo.mymall.product.feign.SearchFeignService;
import net.xiaosaguo.mymall.product.feign.WareFeignService;
import net.xiaosaguo.mymall.product.service.*;
import net.xiaosaguo.mymall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * description: SPU Service
 *
 * @author xiaosaguo
 * @date 2020/06/16 21:28
 */
@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    SpuInfoDescService spuInfoDescService;
    @Resource
    SpuImagesService spuImagesService;
    @Resource
    AttrService attrService;
    @Resource
    ProductAttrValueService productAttrValueService;

    @Resource
    SkuInfoService skuInfoService;
    @Resource
    SkuImagesService skuImagesService;
    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Resource
    BrandService brandService;
    @Resource
    CategoryService categoryService;

    @Resource
    WareFeignService wareFeignService;
    @Resource
    SearchFeignService searchFeignService;

    public static final String DEFAULT_ID = "0";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * description: 添加商品
     * TODO 分布式事物
     *
     * @param spuSaveVO 添加商品 VO
     * @author xiaosaguo
     * @date 2020/06/16 11:23
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {

        // 1. 保存 spu 基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 2. 保存 spu 的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        // 3. 保存 spu 的图片集 pms_spu_images
        List<String> images = spuSaveVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4. 保存 spu 的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrsList = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrsList.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntityList);

        // 5. 保存 spu 的积分信息 sms_spu_bounds
        Bounds bounds = spuSaveVO.getBounds();
        SpuBoundDTO spuBoundDTO = new SpuBoundDTO();
        BeanUtils.copyProperties(bounds, spuBoundDTO);
        spuBoundDTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundDTO);
        if (r.getCode() != 0) {
            log.error("远程保存 spu 积分信息失败");
        }

        // 6. 保存当前 spu 对应的所有 sku 的信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus != null && !skus.isEmpty()) {
            skus.forEach(sku -> {

                // 6.1 sku 的基本信息 pms_sku_info
                String skuDefaultImg = "";
                for (Images img : sku.getImages()) {
                    if (img.getDefaultImg() == 1) {
                        skuDefaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();

                // 6.2 sku 的图片信息 pms_sku_images
                List<SkuImagesEntity> skuImagesEntityList = sku.getImages()
                        .stream()
                        .map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            return skuImagesEntity;
                        })
                        // 没有图片路径的不需要保存
                        .filter(entity -> !StringUtils.isEmpty(entity.getImgUrl()))
                        .collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                // 6.3 sku 的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrList = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);

                // 6.4 sku 的优惠、满减等信息 sms_sku_ladder(打折)/sms_sku_full_reduction(满减)/sms_member_price(会员价)
                SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
                BeanUtils.copyProperties(sku, skuReductionDTO);
                skuReductionDTO.setSkuId(skuId);
                if (skuReductionDTO.getFullCount() > 0 || skuReductionDTO.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionDTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存 sku 优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        // 模糊查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(w -> w.eq("id", key).or().like("spu_name", key));
        }
        // Status 查询
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        // 品牌
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !DEFAULT_ID.equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        // 分类
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !DEFAULT_ID.equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * description: 商品上架
     *
     * @param spuId spu id
     * @author xiaosaguo
     * @date 2020/06/20 02:47
     */
    @Override
    public void up(Long spuId) {

        // 组装 es 需要的数据
        // 1. 查出当前 spuId 对应的所有 sku 信息，品牌的名字
        List<SkuInfoEntity> skuList = skuInfoService.lambdaQuery().eq(SkuInfoEntity::getSpuId, spuId).list();

        // 2. 封装每个 sku 的信息
        // 2.1. 查询当前 sku 的所有可以被检索的规格属性，所有 sku 的检索属性都是相同的，都是 spu 的，处理为 List<SkuEsModel.Attr>
        // 2.1.1 获取 spu 的规格属性，这其中包含了 searchType 为 false 的，需要将 searchType 为 false 过滤掉
        List<ProductAttrValueEntity> productAttrValueList = productAttrValueService
                .lambdaQuery().eq(ProductAttrValueEntity::getSpuId, spuId).list();
        // 转换为 ids
        List<Long> allAttrIds = productAttrValueList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        // 2.1.2 获取到 spu 规格属性中是 searchType 的
        List<AttrEntity> searchTypeAttrList = attrService.lambdaQuery()
                .select(AttrEntity::getAttrId)
                .in(AttrEntity::getAttrId, allAttrIds).eq(AttrEntity::getSearchType, 1)
                .list();
        // 转换为 ids
        List<Long> searchTypeAttrIds = searchTypeAttrList.stream()
                .map(AttrEntity::getAttrId)
                .collect(Collectors.toList());
        // 2.1.3 将 productAttrValueList 中不属于 searchTypeAttrIds 的剔除并转换
        List<SkuEsModel.Attr> collect = productAttrValueList.stream()
                .map(item -> {
                    SkuEsModel.Attr attr = new SkuEsModel.Attr();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .filter(item -> searchTypeAttrIds.contains(item.getAttrId()))
                .collect(Collectors.toList());

        // 2.2. 发送远程调用，查询库存系统是否有库存，批量查询所有 sku 的库存，故放在外面处理，这一步失败不影响整个业务
        // 2.2.1 获取到所有 sku 的 ids
        List<Long> skuIds = skuList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> skuHasStockMap = null;
        try {
            // 2.2.2 远程查询库存系统 skuIds 是否有库存
            R r = wareFeignService.listSkuHasStock(skuIds);
            // 2.2.3 将响应结果转换为 map
            TypeReference<List<SkuHasStockDTO>> typeReference = new TypeReference<>() {
            };
            skuHasStockMap = r.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockDTO::getSkuId, SkuHasStockDTO::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因 {}", e);
        }

        Map<Long, Boolean> finalSkuHasStockMap = skuHasStockMap;
        List<SkuEsModel> upProducts = skuList.stream()
                .map(sku -> {
                    // 遍历组装 SkuEsModel
                    SkuEsModel model = new SkuEsModel();
                    BeanUtils.copyProperties(sku, model);
                    model.setSkuPrice(sku.getPrice());
                    model.setSkuImg(sku.getSkuDefaultImg());

                    // 2.2.4 设置是否有库存
                    if (finalSkuHasStockMap == null) {
                        model.setHasStock(true);
                    } else {
                        model.setHasStock(finalSkuHasStockMap.get(model.getSkuId()));
                    }

                    // 2.3. 热度评分，默认先给个0  TODO 详细逻辑需要和业务逻辑挂钩
                    model.setHotScore(0L);

                    // 2.4. 查询品牌和分类的名字
                    BrandEntity brand = brandService.getById(model.getBrandId());
                    model.setBrandName(brand.getName());
                    model.setBrandImg(brand.getLogo());
                    CategoryEntity category = categoryService.getById(model.getCatalogId());
                    model.setCatalogName(category.getName());

                    // 2.1.4. 查询当前 sku 的所有可以被检索的规格属性
                    model.setAttrs(collect);

                    return model;
                })
                .collect(Collectors.toList());

        // 3. 将数据发送给 es 进行保存
        log.info(upProducts.toString());
        R r = searchFeignService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            // 商品上架成功
            // 修改商品发布状态
            this.lambdaUpdate()
                    .set(SpuInfoEntity::getPublishStatus, ProductConstant.StatusEnum.SPU_UP.getCode())
                    .set(SpuInfoEntity::getUpdateTime, new Date())
                    .eq(SpuInfoEntity::getId, spuId)
                    .update();
            log.info("商品上架成功");
        } else {
            // 商品上架失败
            // TODO 重复调用？接口幂等性：重试机制？
            log.error("商品上架失败，远程调用没报错，响应结果报错");
        }
    }

}